package com.sky.aspect;

import com.sky.anno.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Component
public class AutoFillAspect {
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.anno.AutoFill)")
    public void autoFillPointCut(){}
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint){
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        AutoFill autoFill = methodSignature.getMethod().getAnnotation(AutoFill.class);
        OperationType type = autoFill.type();
        Object[] args = joinPoint.getArgs();
        if (args.length == 0){
            return;
        }
        Object arg = args[0];
        if (type == OperationType.INSERT){
            try {
                arg.getClass().getMethod("setCreateTime", LocalDateTime.class).invoke(arg,LocalDateTime.now());
                arg.getClass().getMethod("setUpdateTime", LocalDateTime.class).invoke(arg,LocalDateTime.now());
                arg.getClass().getMethod("setCreateUser", Long.class).invoke(arg, BaseContext.getCurrentId());
                arg.getClass().getMethod("setUpdateUser", Long.class).invoke(arg, BaseContext.getCurrentId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            try {
                arg.getClass().getMethod("setUpdateTime", LocalDateTime.class).invoke(arg,LocalDateTime.now());
                arg.getClass().getMethod("setUpdateUser", Long.class).invoke(arg, BaseContext.getCurrentId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
